<?php
class CP_IndexController extends XPHP_Controller
{
	/**
	 * Phương thức sẽ thực thi trước khi thực thi sau khi controller được khởi tạo
	 */
	public function _init()
	{
		$this->loadLayout("Administrator");
	}
	
	public function indexAction()
	{
		$this->helper->auth();
		//Lấy tổng số sản phẩm, đơn hàng, thành viên
		$this->view->modelProducts = new Areas_CP_Models_Products();
		$this->view->modelOrders = new Areas_CP_Models_Orders();
		return $this->view();
	}
	
	public function indexAJAX()
	{
		$modelProducts = new Areas_CP_Models_Products();
		$modelOrders = new Areas_CP_Models_Orders();
		$products = $modelProducts->select_all("date_create >= ". XPHP_Date::toTime($this->params['fromDate']) . " and date_create <= ". XPHP_Date::toTime($this->params['toDate']),"date_create DESC");
		$orders = $modelOrders->select_all("date_create >= ". XPHP_Date::toTime($this->params['fromDate']) . " and date_create <= ". XPHP_Date::toTime($this->params['toDate']), "date_create DESC");
		$data['product'] = count($products);
		$data['order'] = count($orders);
		//Xử lý các giá trị ngày, giá.
		$arrProducts = array();
		foreach ($products as $product)
		{
			$arrProducts[$product['id']]['name'] = $product['name'];
			$arrProducts[$product['id']]['price'] = number_format($product['price'],0,",",".");
			$arrProducts[$product['id']]['date_create'] = XPHP_Date::isTheDay($product['date_create']);
		}
		
		$arrOrders = array();
		foreach ($orders as $order)
		{
			$arrOrders[$order['id']]['name'] = $order['fullname'];
			$arrOrders[$order['id']]['date_create'] = XPHP_Date::isTheDay($order['date_create']);
			$arrOrders[$order['id']]['link'] = $this->url->action("detail", "Orders", array($order['id']));
		}
		
		$data['products'] = $arrProducts;
		$data['orders'] = $arrOrders;
		
		return $this->json(array("success" => true,"data" => $data));
	}
	
	/**
	 * [[
	 * model: Areas_CP_Models_Login
	 * ]]
	 */
	public function loginAction()
	{
		$this->unloadLayout();
		return $this->view();	
	}
	
	/**
	 * [[
	 * model: Areas_CP_Models_Login
	 * ]]
	 */
	public function loginAJAX($args)
	{
		if($this->hasModel())
		{
			if($this->model->isValid())
			{
				if($this->model->login())
				{
					$this->helper->session->admin = $this->model->getMember();
					//Redirect về url cũ
					if(isset($args[0]))
						$url = $this->url->decode($args[0]);
					else 
						$url = $this->url->action("index");
					return $this->json(array("success" => true, "url" => $url));
				}
				else
				{
					return $this->json(array("success" => false, "error" => "Tên đăng nhập hoặc mật khẩu không chính xác!"));
				}
			}
			else
			{
				return $this->json(array("success" => false, "error" => "Dữ liệu nhập vào không đúng!"));
			}
		}
	}
	
	public function logoutAction()
	{
		unset($this->helper->session->admin);
		//Redirect về trang đăng nhập
		return $this->redirect("login");
	}
}